package noip.toonsnet.app.preference;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.preference.ListPreference;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;

/**
 * A {@link Preference} that displays a list of entries as
 * a dialog and allows multiple selections
 * <p>
 * This preference will store a string into the SharedPreferences. This string will be the values selected
 * from the {@link #setEntryValues(CharSequence[])} array.
 * </p>
 */
public class ListPreferenceCalendarMultiSelect extends ListPreference {
    private static final String TAG = "ListPreferenceCalendarMultiSelect";
    
    //Need to make sure the SEPARATOR is unique and weird enough that it doesn't match one of the entries.
    //Not using any fancy symbols because this is interpreted as a regex for splitting strings.
    private static final String SEPARATOR = "OV=I=XseparatorX=I=VO";

    private boolean[] mClickedDialogEntryIndices;
    //LinkedHashMap to keep the order
    LinkedHashMap<String, String> map;// = new LinkedHashMap<String, String>();

    public ListPreferenceCalendarMultiSelect(Context context, AttributeSet attrs) {
        super (context, attrs);
        
        Cursor cursor = null;
        
        //get calendars for Android 2.2 and +
        if (cursor == null) {
            try {
            	cursor = context.getContentResolver().query(
            			Uri.parse("content://com.android.calendar/calendars"),
            			new String[] { "_id", "displayname" }, null, null, null);
            } catch (SQLiteException e) {
            	Log.e(TAG, "content://com.android.calendar/calendars", e);
            }
        }
        
        //get calendars for prior Android 2.2 
        if (cursor == null) {
        	try {
        		cursor = context.getContentResolver().query(
        				Uri.parse("content://calendar/calendars"),
        				new String[] { "_id", "displayname" }, null, null, null);
            } catch (SQLiteException e) {
            	Log.e(TAG, "content://calendar/calendars", e);
            }
        }
        
        //get calendars for prior Android 2.2 
        if (cursor == null) {
        	try {
	            cursor = context.getContentResolver().query(
	            		Uri.parse("content://calendarEx/calendars"),
	            		new String[] { "_id", "displayname" }, null, null, null);
	        } catch (SQLiteException e) {
	        	Log.e(TAG, "content://calendarEx/calendars", e);
	        }
        }
        
        //get calendars for prior Android 2.2 
        if (cursor == null) {
        	try {
        		cursor = context.getContentResolver().query(
        				Uri.parse("content://com.android.calendarEx/calendars"),
        				new String[] { "_id", "displayname" }, null, null, null);
	        } catch (SQLiteException e) {
	        	Log.e(TAG, "content://com.android.calendarEx/calendars", e);
	        }
        }
        
        if (cursor != null) {
            cursor.moveToFirst();
            map = new LinkedHashMap<String, String>(cursor.getCount());

            while (cursor.moveToNext()) {
                map.put(Integer.toString(cursor.getInt(0)), cursor.getString(1));
                //Log.w("Calendar", cursor.getString(1));
            }
            
            cursor.close();
        } else {
            map = new LinkedHashMap<String, String>(0);
        }
        
        mClickedDialogEntryIndices = new boolean[getEntries().length];
    }

    @Override
    public void setEntries(CharSequence[] entries) {
        super .setEntries(entries);
        mClickedDialogEntryIndices = new boolean[entries.length];
    }

    public ListPreferenceCalendarMultiSelect(Context context) {
        this (context, null);
    }

    @Override
    protected void onPrepareDialogBuilder(Builder builder) {

        CharSequence[] entries = getEntries();
        CharSequence[] entryValues = getEntryValues();

        if (entries == null || entryValues == null || entries.length != entryValues.length) {
            throw new IllegalStateException("ListPreference requires an entries array and an entryValues array which are both the same length");
        }

        restoreCheckedEntries();
        builder.setMultiChoiceItems(entries,
                mClickedDialogEntryIndices,
                new DialogInterface.OnMultiChoiceClickListener() {
                    public void onClick(DialogInterface dialog, int which, boolean val) {
                        mClickedDialogEntryIndices[which] = val;
                    }
                });
    }

    public static String[] parseStoredValue(CharSequence val) {
        if ("".equals(val) || val == null) {
            return null;
        } else {
            return ((String) val).split(SEPARATOR);
        }
    }

    private void restoreCheckedEntries() {
        CharSequence[] entryValues = getEntryValues();

        String[] vals = parseStoredValue(getValue());
        if (vals != null) {
            for (int j = 0; j < vals.length; j++) {
                String val = vals[j].trim();
                for (int i = 0; i < entryValues.length; i++) {
                    CharSequence entry = entryValues[i];
                    if (entry.equals(val)) {
                        mClickedDialogEntryIndices[i] = true;
                        break;
                    }
                }
            }
        }
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        //        super.onDialogClosed(positiveResult);

        CharSequence[] entryValues = getEntryValues();
        if (positiveResult && entryValues != null) {
            StringBuffer value = new StringBuffer();
            for (int i = 0; i < entryValues.length; i++) {
                if (mClickedDialogEntryIndices[i]) {
                    value.append(entryValues[i]).append(SEPARATOR);
                }
            }

            if (callChangeListener(value)) {
                String val = value.toString();
                if (val.length() > 0) {
                    val = val.substring(0, val.length() - SEPARATOR.length());
                }
                setValue(val);
            }
        }
    }

    @Override
    public CharSequence[] getEntries() {
        if (map.values() != null) {
            String returnedEntries[] = (String[]) map.values().toArray(new String[0]);
            return returnedEntries;
        } else {
            return new String[] {};
        }

    }

    @Override
    public CharSequence[] getEntryValues() {

        Collection<String> entries = new ArrayList<String>();
        for (String iterable_element : map.keySet()) {
            entries.add(iterable_element);
        }
        //String s[] = (String[]) planets.toArray(new String[0]);
        String returnedEntries[] = (String[]) entries.toArray(new String[0]);
        return returnedEntries;// super.getEntries();
    }
}
